package com.qin.dao;

import java.sql.SQLException;
import java.util.List;

import com.qin.entity.Shopping;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;

/**
 * 操作Shopping类
 * @author BestRiven
 *
 */
public class ShoppingDao{

	/**
	 * 插入一条购物车记录
	 * @param shopping 要插入的购物车信息
	 * @return 自增id
	 */
	public Long insertShopping(Shopping shopping) {
		Entity record = Entity.parseWithUnderlineCase(shopping);
		Long insertForGeneratedKey = 0L;
		try {
			insertForGeneratedKey = Db.use().insertForGeneratedKey(record);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return insertForGeneratedKey;
	}
	
	/**
	 * 根据id删除购物车记录
	 * @param id 要删除购物车记录的id
	 * @return 影响行数（0代表失败，1代表影响一行）
	 */
	public int deleteShopping(Long id) {
		String sql = "UPDATE `shopping` SET `status` = 0 WHERE `id` = ?";
		int del = 0;
		try {
			del = Db.use().execute(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return del;
	}
	
	/**
	 * 拿到要修改的购物车的id，根据传过来的图书数量，修改购物车
	 * @param id 购物车的id
	 * @param shopping 图书数量
	 * @return 影响行数（0代表失败，1代表影响一行）
	 */
	public int updateShopping(Long id, Integer num) {
		String sql = "UPDATE `shopping` SET `book_num` = ? WHERE `id` = ?";
		int execute = 0;
		try {
			execute = Db.use().execute(sql, num,id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return execute;
	}
	
	/**
	 * 通过购物车的id查询
	 * @param id
	 * @return
	 */
	public Shopping queryShoppingById(Long id) {
		Entity where = Entity.create("shopping").set("id",id).set("status", 1);
		Shopping find = null;
		try {
			find = Db.use().find(where,new BeanHandler<Shopping>(Shopping.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return find;
	}
	
	/**
	 * 通过用户id和图书id查询购物车记录
	 * @param uid 用户id
	 * @param bid 图书id
	 * @return
	 */
	public Shopping queryShoppingByUserAndBook(Long uid,Long bid) {
		String sql = "SELECT * FROM `shopping` WHERE `user_id` = ? AND `book_id` = ? AND `status` = 1";
		Shopping shopping = null;
		try {
			shopping = Db.use().query(sql, new BeanHandler<Shopping>(Shopping.class), uid,bid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return shopping;
	}
	
	/**
	 * 通过用户的id查出所有的购物车记录
	 * @param id 用户的id
	 * @return 所有的购物车记录
	 */
	public List<Shopping> queryShoppingByUserId(Long id){
		List<Shopping> shoppingCar = null;
		try {
			shoppingCar = Db.use().find(Entity.create("shopping").set("user_id", id).set("status", 1),Shopping.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return shoppingCar;
	}
}
